/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.fedoraaccess.rest;

import cz.mzk.kramerius.fedoraaccess.FedoraServer;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
class ObjectExistsOperation extends AbstractOperation {

    private static final Logger logger = Logger.getLogger(ObjectExistsOperation.class.getName());

    public ObjectExistsOperation(FedoraServer fedoraServer) {
        super(new HttpConnector(fedoraServer, HttpMethod.GET));
    }

    public boolean run(String pid) {
        String request = buildRequest(pid);
        logger.log(Level.FINE, "request: ''{0}''", request);
        try {
            Document resultDoc = connector.processRequestWithXmlResult(request);
            return containsSinglePid(resultDoc);
        } catch (DocumentException ex) {
            logger.log(Level.SEVERE, null, ex);
            return false;
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
            return false;
        }
    }

    private String buildRequest(String pid) {
        StringBuilder builder = new StringBuilder();
        builder.append(getBaseUrl());
        builder.append("/objects?");
        builder.append("query=pid%3D").append(pid);
        //TODO: nema to byt takto?
        //builder.append("query=").append(encodeAttribute("pid=".concat(pid)));
        builder.append("&pid=true&resultFormat=xml");
        return builder.toString();
    }

    private boolean containsSinglePid(Document resultDoc) {
        List<String> pidList = extractPidList(resultDoc);
        return pidList.size() == 1;
    }
}
